
// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

import NECommonKit
import NIMSDK
import UIKit

@objcMembers
open class NEBaseTeamAnnouncementEditViewController: NEBaseViewController, UITextViewDelegate {
    public var team: V2NIMTeam?
    public var announcement: String?
    
    public let textLimit = 1000
    
    public let infoBackView = UIView()
    public let backView = UIView()
    
    public let viewModel = TeamAnnouncementViewModel()
    public weak var delegate: TeamAnnouncementDelegate?
    
    public lazy var headerView: NEUserHeaderView = {
        let header = NEUserHeaderView(frame: .zero)
        header.titleLabel.font = NEConstant.defaultTextFont(14)
        header.titleLabel.textColor = UIColor.white
        header.layer.cornerRadius = 6
        header.clipsToBounds = true
        header.translatesAutoresizingMaskIntoConstraints = false
        return header
    }()
    
    public lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = NEConstant.defaultTextFont(16.0)
        label.textColor = .normalTeamTitleColor
        label.accessibilityIdentifier = "id.userName"
        return label
    }()
    
    public lazy var roleLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = NEConstant.defaultTextFont(13.0)
        label.textColor = .normalTeamSubTitleColor
        label.accessibilityIdentifier = "id.role"
        return label
    }()
    
    public lazy var timeLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = NEConstant.defaultTextFont(13.0)
        label.textColor = .normalTeamSubTitleColor
        label.accessibilityIdentifier = "id.time"
        label.textAlignment = .right
        return label
    }()
    
    /// 公告输入框
    public lazy var textView: UITextView = {
        let textView = UITextView()
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.textColor = NEConstant.hexRGB(0x333333)
        textView.font = NEConstant.defaultTextFont(14.0)
        textView.delegate = self
        textView.textContainerInset = UIEdgeInsets.zero
        textView.layoutManager.allowsNonContiguousLayout = false
        textView.accessibilityIdentifier = "id.announcement"
        return textView
    }()
    
    /// 清除按钮
    public lazy var clearButton: UIButton = {
        let text = UIButton()
        text.translatesAutoresizingMaskIntoConstraints = false
        text.setImage(coreLoader.loadImage("clear_btn"), for: .normal)
        text.addTarget(self, action: #selector(clearText), for: .touchUpInside)
        text.accessibilityIdentifier = "id.clear"
        return text
    }()
    
    /// 字数计数显示
    public lazy var countLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = NEConstant.hexRGB(0xB3B7BC)
        label.font = NEConstant.defaultTextFont(12.0)
        label.accessibilityIdentifier = "id.flag"
        return label
    }()
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        weak var weakSelf = self
        
        viewModel.getCurrentMember(team?.teamId) { member, error in
            if let err = error {
                weakSelf?.view.makeToast(err.localizedDescription)
            }
            weakSelf?.setupUI()
        }
        
    }
    
    /// 布局初始化
    open func setupUI() {
        navigationView.setMoreButtonTitle(localizable("save"))
        navigationView.moreButton.titleLabel?.font = NEConstant.defaultTextFont(14)
        navigationView.addMoreButtonTarget(target: self, selector: #selector(saveAnnouncement))
        if let serverExtension = team?.serverExtension, serverExtension.contains(discussTeamKey) {
            title = localizable("discuss_announcement")
        } else {
            title = localizable("team_announcement")
        }
        
        infoBackView.backgroundColor = .white
        infoBackView.translatesAutoresizingMaskIntoConstraints = false
        infoBackView.clipsToBounds = false
        view.addSubview(infoBackView)
        
        infoBackView.addSubview(headerView)
        infoBackView.addSubview(nameLabel)
        infoBackView.addSubview(roleLabel)
        infoBackView.addSubview(timeLabel)
        
        
        weak var weakSelf = self

        if let url = viewModel.userInTeam?.nimUser?.user?.avatar, !url.isEmpty {
          headerView.sd_setImage(with: URL(string: url), completed: nil)
          headerView.setTitle("")
        } else {
          headerView.image = nil
          headerView.setTitle(viewModel.userInTeam?.showNickInTeam() ?? "")
          headerView.backgroundColor = UIColor.colorWithString(string: viewModel.userInTeam?.nimUser?.user?.accountId)
        }
        nameLabel.text = viewModel.userInTeam?.atNameInTeam()
        

        TeamHelper.announcemenUserInfo(team?.teamId, team?.serverExtension, { user in
            if let user = user {
                if let url = user.member?.nimUser?.user?.avatar, !url.isEmpty {
                    weakSelf?.headerView.sd_setImage(with: URL(string: url), completed: nil)
                    weakSelf?.headerView.setTitle("")
                } else {
                    weakSelf?.headerView.image = nil
                    weakSelf?.headerView.setTitle(user.member?.showNickInTeam() ?? "")
                    weakSelf?.headerView.backgroundColor = UIColor.colorWithString(string: user.member?.nimUser?.user?.accountId)
                }
                weakSelf?.nameLabel.text = user.member?.atNameInTeam()
                weakSelf?.roleLabel.text = TeamHelper.userTitleName(user.member)
                weakSelf?.timeLabel.text = "发布时间：\(user.time ?? "")"
            }
        })
        
        
        backView.backgroundColor = .white
        backView.translatesAutoresizingMaskIntoConstraints = false
        backView.clipsToBounds = false
        
        view.addSubview(backView)
        backView.addSubview(textView)
        backView.addSubview(clearButton)
        backView.addSubview(countLabel)
        
        NSLayoutConstraint.activate([
            countLabel.rightAnchor.constraint(equalTo: backView.rightAnchor, constant: -16),
            countLabel.bottomAnchor.constraint(equalTo: backView.bottomAnchor, constant: -8.0),
        ])
        
        figureTextCount(announcement ?? team?.announcement ?? "")
        
        if getPermission() == false {
            textView.isEditable = false
            rightNavButton.isHidden = true
            navigationView.moreButton.isHidden = true
        }
    }
    
    /// 权限改变
    func getPermission() -> Bool {
        if let ownerId = team?.ownerAccountId, IMKitClient.instance.isMe(ownerId) {
            return true
        }
        if let mode = team?.updateInfoMode, mode == .TEAM_UPDATE_INFO_MODE_ALL {
            return true
        }
        if let member = viewModel.currentTeamMember, member.memberRole == .TEAM_MEMBER_ROLE_MANAGER {
            return true
        }
        return false
    }
    
    /// 保存简介
    func saveAnnouncement() {
        textView.resignFirstResponder()
        weak var weakSelf = self
        if NEChatDetectNetworkTool.shareInstance.manager?.isReachable == false {
            weakSelf?.showToast(commonLocalizable("network_error"))
            return
        }
        // 上传请求
        if let teamid = team?.teamId {
            let text = textView.text ?? ""
            view.makeToastActivity(.center)
            viewModel.updateTeamAnnouncement(teamid, text, team?.serverExtension) { error, announcement, serverExtension in
                NEALog.infoLog(
                    ModuleName + " " + self.className(),
                    desc: "CALLBACK updateTeamAnnouncement " + (error?.localizedDescription ?? "no error")
                )
                weakSelf?.view.hideToastActivity()
                if let err = error {
                    if err.code == protocolSendFailed {
                        weakSelf?.showToast(commonLocalizable("network_error"))
                    } else if error?.code == noPermissionOperationCode {
                        weakSelf?.showToast(localizable("no_permission_tip"))
                    } else {
                        weakSelf?.showToast(localizable("failed_operation"))
                    }
                } else {
                    if let delegate = self.delegate {
                        delegate.updateTeamAnnouncement(announcement: announcement, serverExtension: serverExtension)
                    }
                    weakSelf?.navigationController?.popViewController(animated: true)
                }
            }
        }
    }
    
    /// 计算当前输入字数
    func figureTextCount(_ text: String) {
        textView.text = text
        countLabel.text = "\(text.utf16.count)/\(textLimit)"
        clearButton.isHidden = !getPermission() || text.utf16.count <= 0
    }
    
    /// 清空输入
    func clearText() {
        figureTextCount("")
    }
    
    /// 输入文本变更回调
    open func textViewDidChange(_ textView: UITextView) {
        if let _ = textView.markedTextRange {
            return
        }
        if let text = textView.text {
            figureTextCount(text)
        }
    }
    
    /// 文本变更回调
    /// - Parameter textView: 文本控件对象
    /// - Parameter range: 变更范围
    /// - Parameter text:  变更内容
    public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if !text.isEmpty {
            let finalStr = (textView.text as NSString).replacingCharacters(in: range, with: text)
            if finalStr.utf16.count > textLimit {
                return false
            }
        }
        return true
    }
}
